<template>
  <div class="components-seckill-add-or-update">
    <el-dialog
      v-model="visible"
      :title="!dataForm.seckillId ? $t('crud.addTitle') : $t('live.view')"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="$t('language') === 'English' ? '200px' : '80px'"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item
          :label="$t('group.actName')"
          prop="seckillName"
          maxlength="36"
        >
          <el-input
            v-model.trim="dataForm.seckillName"
            :disabled="!!dataForm.seckillId"
            maxlength="36"
            style="width: 526px"
          />
        </el-form-item>
        <el-form-item
          :label="$t('marketing.activTime')"
          prop="startTime"
        >
          <el-date-picker
            v-model="dataForm.startTime"
            value-format="YYYY-MM-DD"
            type="date"
            style="width: 145px"
            :placeholder="$t('date.start')"
            :end-placeholder="$t('date.end')"
            :disabled="!!dataForm.seckillId || pickerDisabled"
          />
          <el-time-select
            v-model="startTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            style="width: 106px"
            :class="{'time-select': true, 'time-select-clear': !!startTimeValue}"
            :disabled="!!dataForm.seckillId || pickerDisabled"
            :placeholder="$t('user.startDate')"
          />
          <span style="margin: 0 10px">-</span>
          <el-date-picker
            v-model="dataForm.endTime"
            value-format="YYYY-MM-DD"
            type="date"
            style="width: 145px"
            :placeholder="$t('date.end')"
            :disabled="!!dataForm.seckillId || pickerDisabled"
          />
          <el-time-select
            v-model="endTimeValue"
            start="00:00"
            step="00:30"
            end="23:30"
            style="width: 106px"
            :class="{'time-select': true, 'time-select-clear': !!endTimeValue}"
            :disabled="!!dataForm.seckillId || pickerDisabled"
            :placeholder="$t('user.endDate')"
          />
        </el-form-item>
        <el-form-item
          :label="$t('seckill.purcPerPerson')"
          prop="maxNum"
        >
          <el-checkbox
            v-model="hasMaxNum"
            :disabled="!!dataForm.seckillId"
            @click="handlerChangeMaxNum"
          >
            {{ $t('seckill.openPurchaseLimit') }}
          </el-checkbox>
          <span v-show="hasMaxNum">
            {{ $t('seckill.canBePurcPer') }}
            <el-input-number
              v-model="dataForm.maxNum"
              controls-position="right"
              :min="1"
              :max="1000"
              :disabled="!!dataForm.seckillId"
              :precision="0"
            />
            {{ $t('marketing.item') }}
          </span>
        </el-form-item>
        <el-form-item
          :label="$t('seckill.cancelTheOrder')"
          prop="maxCancelTime"
        >
          {{ $t('order.buyer') }}，
          <el-input-number
            v-model="dataForm.maxCancelTime"
            :min="2"
            :max="15"
            controls-position="right"
            :disabled="!!dataForm.seckillId"
            :precision="0"
          />
          {{ $t('seckill.unpaidnutes') }}
        </el-form-item>
        <el-form-item :label="$t('home.product')">
          <el-button
            v-if="!dataForm.seckillId && prod === null"
            plain
            style="float: left"
            @click="prodsSelectHandle()"
          >
            {{ $t('product.select') }}
          </el-button>
          <el-alert
            :title="$t('seckill.warning')"
            type="warning"
            :closable="false"
            style="width: 305px; float: left; height: 40px; margin-left: 10px"
          />
        </el-form-item>
        <el-form-item>
          <el-card
            v-if="prod != null"
            :body-style="{ padding: '0px' }"
            style="height: 160px; width: 120px"
          >
            <ImgShow
              height="104px"
              width="100%"
              :src="prod.pic"
            />
            <div class="card-prod-info-btn">
              <div class="prod-name">
                {{ prod.prodName }}
              </div>
              <div
                v-if="!dataForm.seckillId"
                class="del-btn"
              >
                <span @click="deleteProd">{{ $t('text.delBtn') }}</span>
              </div>
            </div>
          </el-card>
        </el-form-item>
        <el-form-item v-if="skuList.length">
          <div>
            <el-button
              v-if="!dataForm.seckillId"
              link
              type="primary"
              :icon="DocumentChecked"
              class="fz-12"
              @click="switchSet"
            >
              {{ $t('groups.batchSettings') }}
            </el-button>
            <el-form
              v-if="isEdit"
              :inline="true"
              class="demo-form-inline"
              @submit.prevent
            >
              <el-form-item :label="$t('seckill.sellingPrice')">
                <el-input-number
                  v-model="dataForm.price"
                  controls-position="right"
                  :precision="2"
                  :max="1000000000"
                  :min="0"
                />
              </el-form-item>
              <el-form-item :label="$t('marketing.inventory')">
                <el-input-number
                  v-model="dataForm.stocks"
                  controls-position="right"
                  :precision="0"
                  :max="9999999"
                  :min="0"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  class="filter-submitBtn"
                  @click="batchSet"
                >
                  {{
                    $t('crud.filter.submitBtn')
                  }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="default"
                  class="filter-submitBtn"
                  @click="switchSet"
                >
                  {{
                    $t('crud.filter.cancelBtn')
                  }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table
            v-if="skuList.length"
            :data="skuList"
            border
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
            style="width: 100%; margin-top: 20px"
          >
            <el-table-column
              prop="prodName"
              :label="$t('product.prodName')"
              width="250"
            >
              <template #default="scope">
                {{ scope.row.prodName }}
              </template>
            </el-table-column>
            <el-table-column
              prop="price"
              :label="$t('seckill.sellingPrice')"
              :width="$t('language') === 'English' ? '251' : '201'"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.seckillPrice"
                  :precision="2"
                  :step="0.01"
                  :min="0.01"
                  :max="scope.row.price"
                  :disabled="!!(!scope.row.status || dataForm.seckillId)"
                />
                <div>{{ $t('seckill.price') }}：{{ scope.row.price }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="stocks"
              :label="$t('seckill.onHandStock')"
              width="201"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.seckillStocks"
                  type="number"
                  :min="0"
                  :max="9999999"
                  :disabled="!!(!scope.row.status || dataForm.seckillId)"
                  :precision="0"
                />
                <div>{{ $t('seckill.exisocks') }}：{{ scope.row.stocks }}</div>
              </template>
            </el-table-column>
            <el-table-column :label="!dataForm.seckillId ? $t('text.menu') : $t('product.status')">
              <template #default="scope">
                <div v-if="!dataForm.seckillId">
                  <el-button
                    v-if="scope.row.status"
                    link
                    type="primary"
                    :disabled="!!dataForm.seckillId"
                    @click="changeSkuStatus(`${scope.$index}`)"
                  >
                    {{ $t('publics.disable') }}
                  </el-button>
                  <el-button
                    v-else
                    link
                    type="primary"
                    :disabled="!!dataForm.seckillId"
                    @click="changeSkuStatus(`${scope.$index}`)"
                  >
                    {{ $t('shop.ena') }}
                  </el-button>
                </div>

                <div v-else>
                  <el-button
                    v-if="!scope.row.seckillPrice"
                    link
                    type="primary"
                    :disabled="!!dataForm.seckillId"
                    @click="changeSkuStatus(`${scope.$index}`)"
                  >
                    {{ $t('publics.disable') }}
                  </el-button>
                  <el-button
                    v-else
                    link
                    type="primary"
                    :disabled="!!dataForm.seckillId"
                    @click="changeSkuStatus(`${scope.$index}`)"
                  >
                    {{ $t('shop.ena') }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="visible = false"
          >
            {{ $t('crud.filter.cancelBtn') }}
          </div>
          <div
            :class="[!!dataForm.seckillId ? 'disabled-btn' : '', 'default-btn primary-btn']"
            @click="onSubmit(!!dataForm.seckillId)"
          >
            {{ $t('crud.filter.submitBtn') }}
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 商品选择弹窗-->
    <!-- 如果要更改dataUrl，在商品选择组件选择商品后的判断处也要更改一下 -->
    <prods-select
      v-if="prodsSelectVisible"
      ref="prodsSelectRef"
      :is-single="true"
      :data-url="'/seckill/seckill/canSekcillProdPage'"
      @refresh-select-prods="selectSeckillProd"
    />
  </div>
</template>

<script setup>
import { DocumentChecked } from '@element-plus/icons-vue'
import ProdsSelect from '@/components/prods-select/index.vue'
import { getDateTimeRange, getParseTime } from '@/utils/datetime'
import { ElMessage } from 'element-plus'
import { defineEmits, ref, nextTick } from 'vue'
import $t from '@/utils/$t.js'
import http from '@/utils/http.js'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const pickerDisabled = ref(false)
const prodsSelectVisible = ref(false)

const prodsSelectRef = ref(null)
const hasMaxNum = ref(false)
const isEdit = ref(false)
const isError = ref(false)
const dataForm = ref({
  dateRange: [],
  seckillId: null,
  seckillName: null,
  startTime: '',
  endTime: '',
  maxNum: 1,
  hasMaxNum: false,
  maxCancelTime: 2,
  price: null,
  stocks: null
})

const prod = ref(null)
const isSubmit = ref(false)
const skuList = ref([])
const dataFormRef = ref(null)
const tips = ref('')

// 时间验证
const startTimeValue = ref('')
const endTimeValue = ref('')
// eslint-disable-next-line no-unused-vars
const validatorDateRange = (rule, value, callback) => {
  if (
    !startTimeValue.value ||
    !dataForm.value.startTime ||
    !endTimeValue.value ||
    !dataForm.value.endTime
  ) {
    callback(new Error($t('seckill.pleaheyTime')))
  }
  const endTime = dataForm.value.endTime + ' ' + endTimeValue.value + ':00'
  if (!dataForm.value.seckillId && new Date() > Date.parse(endTime)) {
    callback(new Error($t('groups.endTime')))
  } else {
    callback()
  }
}

const dataRule = {
  startTime: [{ required: true, validator: validatorDateRange, trigger: 'blur' }],
  seckillName: [{ required: true, message: $t('seckill.evenBeEmpty'), trigger: 'blur' }],
  maxCancelTime: [{ required: true, message: $t('seckill.theOrionEmpty'), trigger: 'blur' }]
}

const init = seckillId => {
  dataForm.value.seckillId = seckillId || 0
  visible.value = true
  pickerDisabled.value = false
  isSubmit.value = false
  nextTick(() => {
    dataFormRef.value.resetFields()
    prod.value = null
    skuList.value = []
    hasMaxNum.value = false
    const datetimeRange = getDateTimeRange()
    dataForm.value.startTime = datetimeRange.startTime
    dataForm.value.endTime = datetimeRange.endTime
    startTimeValue.value = datetimeRange.currentTime
    endTimeValue.value = datetimeRange.currentTime
    if (dataForm.value.seckillId) {
      http({
        url: http.adornUrl('/seckill/seckill/info/' + dataForm.value.seckillId),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.value = data.seckill
        startTimeValue.value = dataForm.value.startTime ? dataForm.value.startTime.substring(11, dataForm.value.startTime.length - 3) : ''
        endTimeValue.value = dataForm.value.endTime ? dataForm.value.endTime.substring(11, dataForm.value.endTime.length - 3) : ''
        dataForm.value.startTime = getParseTime(dataForm.value.startTime, '{y}-{m}-{d}')
        dataForm.value.endTime = getParseTime(dataForm.value.endTime, '{y}-{m}-{d}')
        hasMaxNum.value = data.seckill.maxNum > 0
        prod.value = data.prod
        getSkuList(data.prod.prodId, data.seckillSkus)
      })
    }
  })
}
defineExpose({ init })
const switchSet = () => {
  isEdit.value = !isEdit.value
}
const batchSet = () => {
  skuList.value.forEach(sku => {
    if (dataForm.value.price) {
      sku.seckillPrice = dataForm.value.price
    }
    if (dataForm.value.stocks >= 0) {
      sku.seckillStocks = dataForm.value.stocks
    }
  })
  isEdit.value = false
  dataForm.value.price = 0
  dataForm.value.stocks = 0
}
const getSkuList = (prodId, seckillSkus) => {
  http({
    url: http.adornUrl('/sku/getAllSkuList'),
    method: 'get',
    params: http.adornParams({
      prodId
    })
  }).then(({ data }) => {
    if (seckillSkus) {
      data.forEach(sku => {
        seckillSkus.forEach(seckillSku => {
          if (sku.skuId === seckillSku.skuId) {
            sku.seckillStocks = seckillSku.seckillStocks
            sku.seckillPrice = seckillSku.seckillPrice
          }
        })
      })
    }
    skuList.value = data
  })
}
/**
 * 判断sku中的商品价格与库存是否有填写
 */
const checkSku = () => {
  isError.value = false
  skuList.value.forEach(element => {
    if (!element.seckillPrice && element.status === 1) {
      isError.value = true
      tips.value = $t('seckill.commoBeEmpty')
      return true
    }
    if (!element.seckillStocks && element.seckillStocks !== 0 && element.status === 1) {
      isError.value = true
      tips.value = $t('seckill.commodiBeEmpty')
      return true
    }
  })
}
// 表单提交
const onSubmit = status => {
  if (status) {
    return
  }
  // 秒杀不能更新
  if (dataForm.value.seckillId) {
    visible.value = false
    return
  }

  dataFormRef.value.validate(valid => {
    if (valid) {
      const startDate =
        dataForm.value.startTime && startTimeValue.value ? dataForm.value.startTime + ' ' + startTimeValue.value + ':00' : ''
      const endDate =
        dataForm.value.endTime && endTimeValue.value ? dataForm.value.endTime + ' ' + endTimeValue.value + ':00' : ''
      if (endDate <= startDate) {
        ElMessage({
          message: $t('marketing.eventEndanStartTime'),
          type: 'error'
        })
        return
      }
      if (!prod.value) {
        ElMessage({
          message: $t('seckill.pleaSenProc'),
          type: 'error'
        })
        return
      }
      if (!hasMaxNum.value) {
        dataForm.value.maxNum = -1
      }
      // 判断sku中的商品价格与库存是否有填写
      checkSku()
      if (isError.value) {
        ElMessage.error(tips.value)
        return
      }
      const startTime = dataForm.value.startTime
      const endTime = dataForm.value.endTime
      dataForm.value.startTime = startDate
      dataForm.value.endTime = endDate
      dataForm.value.prodId = prod.value.prodId
      dataForm.value.seckillSkus = skuList.value.filter(sku => sku.status)
      // 禁用所有商品规格时，进行警告
      if (!dataForm.value.seckillSkus || dataForm.value.seckillSkus.length === 0) {
        ElMessage({
          message: $t('marketing.productSpecification'),
          type: 'error'
        })
        return
      }
      const paramData = Object.assign({}, dataForm.value)
      paramData.hasMaxNum = hasMaxNum.value ? 1 : 0
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      pickerDisabled.value = true
      http({
        url: http.adornUrl('/seckill/seckill'),
        method: 'post',
        data: http.adornData(paramData)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit.value = false
        pickerDisabled.value = false
      })
      dataForm.value.startTime = startTime
      dataForm.value.endTime = endTime
    }
  })
}

// 显示添加指定商品弹框
const prodsSelectHandle = () => {
  prodsSelectVisible.value = true
  nextTick(() => {
    prodsSelectRef.value?.init(dataForm.value?.discountProds)
  })
}
const handlerChangeMaxNum = val => {
  if (val) {
    dataForm.value.maxNum = 1
  } else {
    dataForm.value.maxNum = -1
  }
}
// 添加指定商品
const selectSeckillProd = prods => {
  if (prods.length) {
    prod.value = prods[0]
    getSkuList(prods[0].prodId)
  } else {
    skuList.value = []
    prod.value = null
  }
}
const deleteProd = () => {
  prod.value = null
  skuList.value = []
}
const changeSkuStatus = tagIndex => {
  skuList.value[tagIndex].status = skuList.value[tagIndex].status ? 0 : 1
}
</script>

<style lang="scss" scoped>
:deep(.el-input__inner) {
  border: none !important;
  padding-left: 0 !important;
}
.components-seckill-add-or-update{
  .fz-12{
    font-size: 12px;
  }

  :deep(.time-select.el-select ){
    .el-input .el-select__caret.el-icon{
      display: none;
    }
    &.time-select-clear:hover .el-input .el-select__caret.el-icon{
      display: flex;
    }
  }
}
</style>
